package com.JUC;

import java.util.concurrent.*;

public class JUC14_ForkJoin {
    public static void main(String[] args) throws Exception{
        // 线程操作资源类
        MyTask task = new MyTask(1, 100);
        // 获取分支合并池
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        // 提交池中任务，获得任务对象
        ForkJoinTask<Integer> forkJoinTask = forkJoinPool.submit(task);
        // 通过 .get() 方法获得任务的结果
        System.out.println(forkJoinTask.get());
        // 关闭池
        forkJoinPool.shutdown();
    }
}
// 继承 RecursiveTask 覆写 compute 方法，写出处理任务的具体操作
class MyTask extends RecursiveTask<Integer>{
    //设置以下阈值，一个最小的问题的规模
    private static final Integer value = 10;
    private int begin;
    private int end;
    private int result;

    public MyTask(int begin, int end) {
        this.begin = begin;
        this.end = end;
    }

    // 进行计算
    @Override
    protected Integer compute() {
        if (end - begin >= value){
            for (int i = begin; i <= end; i++){
                result += i;
            }
        }else {
            int mid = (end + begin) / 2;
            MyTask task1 = new MyTask(begin,mid);
            MyTask task2 = new MyTask(mid+1,end);
            // 进行递归，分治
            task1.fork();
            task2.fork();
            // 合并
            result = task1.join()+task2.join();
        }
        return result;
    }
}
